package com.bodacn.keypoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.serialport.SerialPort;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import static android.os.Environment.getDataDirectory;
import static android.os.Environment.getExternalStorageDirectory;
import static java.lang.Integer.*;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener,FragmentC.FragmentCCallBack,FragmentE.FragmentECallBack,FragmentM.FragmentMCallBack,
        FragmentL.FragmentLCallBack, FragmentFabric.FragmentFabricCallBack,Runnable
{
    public static final int getParamFragmentA = 701;
    public static final int getParamFragmentB = 702;
    public static final int getParamFragmentC = 703;
    public static final int getParamFragmentD = 704;
    public static final int getParamFragmentE = 705;
    public static final int getParamFragmentF = 706;
    public static final int getParamFragmentG = 707;
    public static final int getParamFragmentH = 708;
    public static final int getParamFragmentI = 709;
    public static final int getParamFragmentJ = 710;
    public static final int getParamFragmentK= 711;
    public static final int getParamFragmentL= 712;
    public static final int getParamFragmentM= 713;
    public static final int getParamFragmentN= 714;
    public static final int MSG_UpdateSocket=8001;
    private Timer timer;
    private TimerTask timetask;
    TextToSpeech textToSpeech;
    boolean SocketConnected=false;
    //全局变量
    String SaveFilePath="",SaveDBFolder="/DB";
    public static final String DB_Name ="bdmes.db";
    //全局变量
    String STORE_NAME = "Settings";
    //存放当前Fragment
    private Fragment mContent;
    SQLiteDatabase mainDB;
    private FragmentManager fragmentManager=getSupportFragmentManager();

    @Override
    public void FragmentFabricWorkAndTransParams(Map<String, Object> Params) {

    }


    class FragmentStruct{
        Fragment frgmt;
        String ident;
    }
    private List<FragmentStruct> mFragments=new ArrayList<FragmentStruct>();//fragment列表;
    int curFragmentIndex = 0;//当前显示页面;
    //服务器地址
    String language="";
    String serviceUrl="http://192.168.10.12/tvservice";
    String serviceUrlExt  = "/BDService.asmx?wsdl";
    String curLoginUserNo,curLoginUser,curFactory, curDepartNo,curDepart,curLoginTime,CPUID,BoardNo;//操作员所属部门等信息;
    JSONArray curUserPower;
    int curOperateTime =600,SpaceSec=15,SwitchCount=5;//工作分钟
    static int[] WeightArray=new int[10];
    int curPlaceCount=60;//工位数;
    //界面按钮;
    TextView txt_titleInv,txt_funcA,txt_funcB, txt_funcC, txt_funcD, txt_funcE,txt_funcF,txt_funcG,txt_funcH,txt_funcI,txt_funcJ,txt_funcK,txt_funcL,txt_funcM,txt_funcN,txt_funcO,txt_funcFabric;
    TextView title_userNo,title_userName,title_depart, title_ConnectState;
    Button btn_LoginUser, btn_LoginClose;
    ImageView titleImgView;
    Toast curToast;
    private ProgressDialog waitDialog = null;
    //用于将Activity中的参数传给Fragment
    private Map<String,Object> loginParams=new HashMap<String,Object>();
    static boolean receiveFlag=false;
    static boolean haveCardNo=false;
    static SerialPort mSerialPort = null;
    static FileInputStream mInputStream = null;
    static boolean ExitRun=false;
    static String CardNo="";
    static boolean AllowRepeat=true;
    static int baudrate=9600;
    static int parity=0;
    String PrWeight="";
    //广播消息
    /*接收广播端的socket*/
    private MulticastSocket socket;
    private int udpPort=40000;
    String multicastHost="224.0.0.1";//广播地址;
    InetAddress receiveAddress;
    public static final String SOCKER_ACTION = "com.bodacn.keypoint.Control";
    public static final String SOCKER_RCV = "com.bodacn.keypoint.ReceiveStr";



    SocketReceiver socketReceiver;
    public class SocketReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("BroadcastReceiver:SocketReceiver");
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if(action.equals(SOCKER_RCV)) {
                String url = intent.getExtras().getString("action");
                if(url.equals("ClientIP")) {
                    String strIP = intent.getExtras().getString("content");
                    System.out.println("ClientIP---"+strIP);
                    SocketConnected=true;
                }
                else if(url.equals("RcvStr")) {
                    String strContent = intent.getExtras().getString("content");
                    System.out.println("RcvStr:"+strContent);
                    Map<String,Object> Params=new HashMap<String,Object>();
                    Params.put("ParamComm","Answer");
                    Params.put("ParamValue",strContent);
                    if (curFragmentIndex!=-1) {
                        if (mFragments.get(curFragmentIndex).ident.equals("FragmentL")) {
                            transParamsListenerL.TransParams(Params);
                        } else{
                            if (mFragments.get(curFragmentIndex).ident.equals("FragmentE")) {
                                transParamsListenerE.TransParams(Params);
                            }
                        }
                    }
                }
                else if(url.equals("Disconnect")) {
                    SocketConnected=false;
                    String strContent = intent.getExtras().getString("content");
                    System.out.println("Disconnect---"+strContent);
                    Intent sendIntent = new Intent(SOCKER_ACTION);
                    sendIntent.putExtra("ACTION", "reconnect");
                    // 发送广播，将被Activity组件中的BroadcastReceiver接收到
                    sendBroadcast(sendIntent);
                }
                else if(url.equals("ReturnMsg")) {
                    String strContent = intent.getExtras().getString("content");
                    System.out.println("ReturnMsg---"+strContent);
                    Toast.makeText(getApplicationContext(),strContent,Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    //启动定时器;
    private void startTimer(){
        if (timer==null) {
            timer = new Timer();
            System.out.println("onCreate timer---------------------------------2.1");
            //定时任务;
            if (timetask == null) {
                timetask = new TimerTask() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = MSG_UpdateSocket;
                        mainHandler.sendMessage(message);
                    }
                };
            }
            System.out.println("onCreate timer---------------------------------2.2");
            timer.schedule(timetask, 1000, 1000);
        }
    }
    //停止计时器;
    private void stopTimer(){
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timetask != null) {
            timetask.cancel();
            timetask = null;
        }
        System.out.println("startTimer five---------------------------------Start");
    }

    //FragmentC回调;
    @Override
    public void FragmentCWorkAndTransParams(Map<String, Object> Params) {
        //根据获取的参数，判断需要执行的事件;
        String paramComm,paramValue;
        //消息约定FragmentIndex，WorkCodeIndex，ParamObject;
        if (Params!=null)
        {
            //根据参数调用相应功能;
            paramComm=Params.get("ParamComm").toString();
            //进入工序分配界面;
            if (paramComm=="Speech")
            {
                paramValue=Params.get("Text").toString();
                textToSpeech.speak(paramValue, TextToSpeech.QUEUE_FLUSH, null);
            }

        }
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //左右翻页;
        System.out.println("keyCode:"+keyCode);
        if (keyCode==24) {
            //发送消息到C类;
            sendParamFragmentCWeight("0");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    //FragmentM回调;
    @Override
    public void FragmentMWorkAndTransParams(Map<String, Object> Params) {
        //根据获取的参数，判断需要执行的事件;
        String paramComm,paramValue;
        System.out.println("FragmentMWorkAndTransParams 回调");
        //消息约定FragmentIndex，WorkCodeIndex，ParamObject;
        if (Params!=null)
        {
            System.out.println("FragmentMWorkAndTransParams 参数正常");
            //根据参数调用相应功能;
            paramComm=Params.get("ParamComm").toString();
            //进入工序分配界面;
            if (paramComm=="Speech")
            {
                System.out.println("FragmentMWorkAndTransParams 执行语音播报");
                paramValue=Params.get("Text").toString();
                textToSpeech.speak(paramValue, TextToSpeech.QUEUE_FLUSH, null);
            }

        }
    }
    //FragmentE回调;
    @Override
    public void FragmentEWorkAndTransParams(Map<String, Object> Params) {
        //根据获取的参数，判断需要执行的事件;
        String paramComm,paramValue;
        //消息约定FragmentIndex，WorkCodeIndex，ParamObject;
        if (Params!=null)
        {
            //根据参数调用相应功能;
            paramComm=Params.get("ParamComm").toString();
            //进入工序分配界面;
            if (paramComm=="CardNo")
            {
                paramValue=Params.get("ParamValue").toString();
                Log.d("Main<-"+paramComm,paramValue);
                haveCardNo=true;
                CardNo=paramValue;
                Log.d("CardNo:",CardNo);
            }
            if (paramComm=="Repeat")
            {
                paramValue=Params.get("ParamValue").toString();
                Log.d("Main<-"+paramComm,paramValue);
                AllowRepeat=paramValue.equals("T");
            }
            if (paramComm=="SendTask")
            {
                paramValue=Params.get("ParamValue").toString();
                Intent sendIntent = new Intent(SOCKER_ACTION);
                sendIntent.putExtra("ACTION", "sendmsg");
                sendIntent.putExtra("CONTENT", paramValue);
                // 发送广播，将被Activity组件中的BroadcastReceiver接收到
                sendBroadcast(sendIntent);
            }

        }
    }


    @Override
    public void FragmentLWorkAndTransParams(Map<String, Object> Params) {
        //根据获取的参数，判断需要执行的事件;
        String paramComm,paramValue;
        //消息约定FragmentIndex，WorkCodeIndex，ParamObject;
        if (Params!=null)
        {
            //根据参数调用相应功能;
            paramComm=Params.get("ParamComm").toString();
            if (paramComm=="SendTask")
            {
                paramValue=Params.get("ParamValue").toString();
                Intent sendIntent = new Intent(SOCKER_ACTION);
                sendIntent.putExtra("ACTION", "sendmsg");
                sendIntent.putExtra("CONTENT", paramValue);
                // 发送广播，将被Activity组件中的BroadcastReceiver接收到
                sendBroadcast(sendIntent);
            }

        }
    }


    //发送命令;
    private void sendSocket(String paramComm){
        udpBroadCast send=new udpBroadCast(paramComm);
        send.start();
    }
    /* 发送udp多播 */
    private  class udpBroadCast extends Thread {
        MulticastSocket sender = null;
        DatagramPacket dj = null;
        InetAddress group = null;
        byte[] data = new byte[1024];
        public udpBroadCast(String dataString) {
            data = dataString.getBytes();
        }
        @Override
        public void run() {
            try {
                sender = new MulticastSocket();
                group = InetAddress.getByName(multicastHost);
                dj = new DatagramPacket(data,data.length,group,udpPort);
                sender.send(dj);
                sender.close();
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 打开串口的方法
     */
    public static void openSrialPort(){
        Log.i("调试输出","打开串口");
        try {
            //创建串口485;
            if (mSerialPort!=null) mSerialPort.close();
            //速率19200,偶校验(为了同PLC协同)
            mSerialPort = new SerialPort(new File("/dev/ttySAC0"), baudrate,parity,8,1);
            if (mInputStream!=null) mInputStream.close();
            mInputStream = (FileInputStream) mSerialPort.getInputStream();
            receiveFlag=true;
            //receiveSerialPort();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *关闭串口的方法
     * 关闭串口中的输入输出流
     * 然后将flag的值设为flag，终止接收数据线程
     */
    public static void closeSerialPort(){
        Log.i("调试输出","关闭串口");
        try {
            receiveFlag = false;
            if (mSerialPort!=null) mSerialPort.close();
            if(mInputStream != null) {
                mInputStream.close();
                mInputStream=null;
            }
            mSerialPort=null;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {
        long startTime=0;
        byte recBuffer[]=new byte[1024];
        byte sendBuffer[]=new byte[1024];
        startTime=System.currentTimeMillis();
        //判断需发送的内容;
        while (!ExitRun)
        {
            //只有缝制上线开着，才接收;
            if (curFragmentIndex!=-1){
                if (mFragments.get(curFragmentIndex).ident.equals("FragmentL")) {
                    //*发送刷新
                    if (System.currentTimeMillis()-startTime > 10000) {
                        System.out.println("发送刷新命令:FragmentL");
                        //复位时间
                        startTime = System.currentTimeMillis();
                        sendParamFragmentLCmd("RefreshRACK");
                    }
                }
                if (mFragments.get(curFragmentIndex).ident.equals("FragmentO")) {
                    //*发送刷新
                    if (System.currentTimeMillis()-startTime > 10000) {
                        System.out.println("发送刷新命令:FragmentO");
                        //复位时间
                        startTime = System.currentTimeMillis();
                        sendParamFragmentOCmd("RefreshRACK");
                    }
                }
                if (mFragments.get(curFragmentIndex).ident.equals("FragmentC")||mFragments.get(curFragmentIndex).ident.equals("FragmentFabric")) {
                    if (receiveFlag == true) {
                        //发送命令等待接收;
                        if (mInputStream != null) {
                            try {
                                //防止数据分段;
                                try {
                                    if (receiveFlag && (mInputStream.available() == 0)) {
                                        System.currentTimeMillis();
                                        continue;
                                    } else {
                                        Thread.sleep(50);
                                    }
                                } catch (InterruptedException e) {
                                    Log.d("run()", "获取数据出错");
                                    e.printStackTrace();
                                }
                                //检查是否有数据;
                                int size = 0;
                                if (receiveFlag == true) size = mInputStream.read(recBuffer);
                                if (size > 0 && receiveFlag) {
                                    String recInfo = bytesToHexString(recBuffer, size);
                                    Log.e("recInfo", recInfo);
                                    System.currentTimeMillis();
                                    if ((recBuffer[0] == 0x77) && (recBuffer[1] == 0x6E)) {
                                        byte[] b = {recBuffer[3], recBuffer[4], recBuffer[5], recBuffer[6], recBuffer[7], recBuffer[8], recBuffer[9]};
                                        String weight = new String(b);
                                        weight = weight.replace(" ", "");
                                        Log.e("weight:", weight);
                                        if (Float.valueOf(weight) < 0) weight = "0";
                                        weight = String.valueOf(Math.round(Float.valueOf(weight) * 1000));
                                        if (PrWeight != weight) {
                                            PrWeight = weight;
                                            if (mFragments.get(curFragmentIndex).ident.equals("FragmentC")) sendParamFragmentCWeight(weight);
                                            if (mFragments.get(curFragmentIndex).ident.equals("FragmentFabric")) sendParamFragmentFabricWeight(weight);
                                        }
                                    }
                                    mInputStream.reset();
                                    /*
                                    System.currentTimeMillis();
                                    byte[] b={recBuffer[4],recBuffer[5],recBuffer[6],recBuffer[7],recBuffer[8],recBuffer[9]};
                                    String weight= new String (b);
                                    weight=weight.replace(" ","");
                                    Log.e("weight:",weight);
                                    if (Integer.valueOf(weight)<0) weight="0";
                                    weight=String.valueOf(Integer.valueOf(weight));
                                    //检查是否需要发出;
                                    if (checkWeight(2,Integer.valueOf(weight))) sendParamFragmentCWeight(weight);
                                    */
                                }
                            } catch (IOException e) {
                            }
                        }
                    } else {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            else {
                try {
                    if (mInputStream!=null) mInputStream.reset();
                } catch (IOException e) {
                }
            }
        }
    }

   //检查是否稳定;
    public static boolean checkWeight(int len,int weightParam){
        //System.out.println("len:"+len+" weightParam:"+weightParam);
        int totalWeight=0;
        for (int i=0;i<len;i++){
            totalWeight=totalWeight+WeightArray[i];
        }
        //System.out.println("totalWeight:"+totalWeight);
        for (int i=len;i>0;i--){
            WeightArray[i]=WeightArray[i-1];
        }
        WeightArray[0]=weightParam;
        //System.out.println(WeightArray);
        //System.out.println(Float.valueOf(totalWeight)/len*0.95);
        //System.out.println(Float.valueOf(totalWeight)/len*1.05);
        if ((weightParam>=(Float.valueOf(totalWeight)/len*0.95))&&(weightParam<=(Float.valueOf(totalWeight)/len*1.05))) return true;
        else return false;
    }
    //计算异或
    public static byte getXor(byte[] datas,int len) {
        byte temp = datas[0];
        for (int i = 1; i < datas.length; i++) {
            temp ^= datas[i];
        }
        return temp;
    }

    /**
     * 计算CRC16校验码*
     * @param bytes 字节数组
     * @return {@linkstring} 校验码
     * @since 1.0
     */
    public static int getCRC(byte[] bytes,int len) {
        int CRC = 0x0000ffff;
        int POLYNOMIAL = 0x0000a001;
        int i, j;
        for (i = 0; i < len; i++) {
            CRC ^= ((int) bytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((CRC & 0x00000001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }
        return CRC;
    }
    /**
     * byte[]数组转换为16进制的字符串
     *
     * @param bytes 要转换的字节数组
     * @return 转换后的结果
     */
    private static String bytesToHexString(byte[] bytes,int size) {
        StringBuilder sb = new StringBuilder();
        //for (int i = 0; i < bytes.length; i++) {
        for (int i = 0; i < size; i++) {
            String hex = toHexString(0xFF & bytes[i]).toUpperCase();
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex+" ");
        }
        return sb.toString();
    }

    /**
     * 将byte转换为一个长度为8的byte数组，数组每个值代表bit
     */
    public static byte[] getBitArray(byte b) {
        byte[] array = new byte[8];
        for (int i = 7; i >= 0; i--) {
            array[i] = (byte)(b & 1);
            b = (byte) (b >> 1);
        }
        return array;
    }
    /**
     * 把byte转为字符串的bit
     */
    public static String byteToBit(byte b) {
        return ""
                + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
                + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
                + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
                + (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
    }

    //发送消息;
    public static void serialSendBytes(byte[] paramBytes,int paramSize) {
        FileOutputStream mOutputStream;
        byte[] sendBytes= new byte[paramSize];
        for (int i=0;i<paramSize;i++) sendBytes[i]=paramBytes[i];
        String tmpCmdStr;
        if (mSerialPort!=null) {
            try {
                mOutputStream = (FileOutputStream) mSerialPort.getOutputStream();
                //tmpCmdStr=bytesToHexString(sendBytes,paramSize);
                //Log.d("SEND-Start", tmpCmdStr);
                //DeviceIO.write("/sys/devices/platform/x4418-rs485/state", "1");
                mOutputStream.write(sendBytes);
                //Thread.sleep(15);
                //DeviceIO.write("/sys/devices/platform/x4418-rs485/state", "0");
                //Log.d("SEND-Over", tmpCmdStr);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //---------------------------接口申明及调用------------------------开始;
    //A:定义一个传参接口;
    public  interface OnTransParamsListenerA{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerA transParamsListenerA;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerA(OnTransParamsListenerA transParamsListener){
        this.transParamsListenerA=transParamsListener;
    }
    //B:定义一个传参接口;
    public  interface OnTransParamsListenerB{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerB transParamsListenerB;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerB(OnTransParamsListenerB transParamsListener){
        this.transParamsListenerB=transParamsListener;
    }
    //C:定义一个传参接口;
    public  interface OnTransParamsListenerC{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerC transParamsListenerC;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerC(OnTransParamsListenerC transParamsListener){
        this.transParamsListenerC=transParamsListener;
    }
    //D:定义一个传参接口;
    public  interface OnTransParamsListenerD{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerD transParamsListenerD;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerD(OnTransParamsListenerD transParamsListener){
        this.transParamsListenerD=transParamsListener;
    }
    //E:定义一个传参接口;
    public  interface OnTransParamsListenerE{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerE transParamsListenerE;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerE(OnTransParamsListenerE transParamsListener){
        this.transParamsListenerE=transParamsListener;
    }
    //F定义一个传参接口;
    public  interface OnTransParamsListenerF{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerF transParamsListenerF;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerF(OnTransParamsListenerF transParamsListener){
        this.transParamsListenerF=transParamsListener;
    }
    //G定义一个传参接口;
    public  interface OnTransParamsListenerG{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerG transParamsListenerG;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerG(OnTransParamsListenerG transParamsListener){
        this.transParamsListenerG=transParamsListener;
    }
    //H定义一个传参接口;
    public  interface OnTransParamsListenerH{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerH transParamsListenerH;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerH(OnTransParamsListenerH transParamsListener){
        this.transParamsListenerH=transParamsListener;
    }
    //I定义一个传参接口;
    public  interface OnTransParamsListenerI{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerI transParamsListenerI;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerI(OnTransParamsListenerI transParamsListener){
        this.transParamsListenerI=transParamsListener;
    }
    //J定义一个传参接口;
    public  interface OnTransParamsListenerJ{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerJ transParamsListenerJ;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerJ(OnTransParamsListenerJ transParamsListener){
        this.transParamsListenerJ=transParamsListener;
    }
    //K定义一个传参接口;
    public  interface OnTransParamsListenerK{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerK transParamsListenerK;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerK(OnTransParamsListenerK transParamsListener){
        this.transParamsListenerK=transParamsListener;
    }
    //K定义一个传参接口;
    public  interface OnTransParamsListenerL{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerL transParamsListenerL;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerL(OnTransParamsListenerL transParamsListener){
        this.transParamsListenerL=transParamsListener;
    }
    //K定义一个传参接口;
    public  interface OnTransParamsListenerM{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerM transParamsListenerM;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerM(OnTransParamsListenerM transParamsListener){
        this.transParamsListenerM=transParamsListener;
    }
    //K定义一个传参接口;
    public  interface OnTransParamsListenerN{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerN transParamsListenerN;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerN(OnTransParamsListenerN transParamsListener){
        this.transParamsListenerN=transParamsListener;
    }
    //K定义一个传参接口;
    public  interface OnTransParamsListenerO{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerO transParamsListenerO;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerO(OnTransParamsListenerO transParamsListener){
        this.transParamsListenerO=transParamsListener;
    }
    //---------------------\\\\\\各Fragment回调实现//////-------------------------;
    //K定义一个传参接口;
    public  interface OnTransParamsListenerFabric{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerFabric transParamsListenerFabric;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerFabric(OnTransParamsListenerFabric transParamsListener){
        this.transParamsListenerFabric=transParamsListener;
    }
    //---------------------\\\\\\各Fragment回调实现//////-------------------------;
    //核心设置的代码
    protected void switchLanguage() {
        //读取配置文件-设置语言
        SharedPreferences settings = getSharedPreferences(STORE_NAME, MODE_PRIVATE);
        serviceUrl=settings.getString("serviceUrl",serviceUrl);
        language=settings.getString("language",language);
        //获取资源
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        switch (language) {
            case "zh":
                config.locale = new Locale("zh","");
                resources.updateConfiguration(config, dm);
                break;
            case "en":
                config.locale = new Locale("en","");
                resources.updateConfiguration(config, dm);
                break;
            case "km":
                config.locale = new Locale("km","");
                resources.updateConfiguration(config, dm);
                break;
            default:
                config.locale = new Locale("zh","");
                resources.updateConfiguration(config, dm);
                break;
        }
    }

    class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {
                System.out.println("onInit: TTS引擎初始化成功");
            }
            else{
                System.out.println("onInit: TTS引擎初始化失败");
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置语言;
        switchLanguage();
        //语音播报;
        //voice_speed:最快语速1.5";
        //voice_pitch:最高音调2.0";
        textToSpeech=new TextToSpeech(this,new TTSListener());
        textToSpeech.setPitch(1.5f); // 在系统设置里也可以修改音调
        //创建目录;
        try{
            //数据库初始化;
            mainDB = openOrCreateDatabase(DB_Name, this.MODE_PRIVATE, null);
            //取存储路径;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                //SD卡准备好的话，优先存储;
                SaveFilePath = getExternalStorageDirectory().toString();
                Log.d("msg","用存储卡:"+SaveFilePath);
            }
            else{
                //系统内部Flash;
                SaveFilePath =this.getFilesDir().toString();
                Log.d("msg","用系统目录:"+SaveFilePath);
            }
            //组织并判断是否需要创建Root目录;
            SaveFilePath = SaveFilePath +"/BDMES";
            Log.d("msg","存储目录为:"+SaveFilePath);
            //判断是否需要创建BDMES根目录;
            if (isExternalStorageWritable()==true) {
                //主目录;
                File file = new File(SaveFilePath);
                if (!file.isDirectory()) file.mkdir();
                Log.d("msg","目录创建成功:"+ SaveFilePath );
                //数据库目录
                file = new File(SaveFilePath +SaveDBFolder);
                if (!file.isDirectory()) file.mkdir();
                Log.d("msg","目录创建成功:"+ SaveFilePath +SaveDBFolder);
            }
            //设置页面;
            setContentView(R.layout.activity_main);
            //获取登陆参数
            Bundle paramBundle = this.getIntent().getExtras();
            System.out.println(paramBundle);
            curLoginUserNo=paramBundle.getString("LoginUserNo");
            curLoginUser=paramBundle.getString("LoginUser");
            curLoginTime=paramBundle.getString("LoginTime");
            curFactory=paramBundle.getString("CurFactory");
            curDepartNo=paramBundle.getString("CurDepartNo");
            curDepart=paramBundle.getString("CurDepart");
            curPlaceCount=paramBundle.getInt("PlaceCount");
            curOperateTime=paramBundle.getInt("OperateTime");
            serviceUrl=paramBundle.getString("serviceUrl");
            serviceUrlExt=paramBundle.getString("serviceUrlExt");
            BoardNo=paramBundle.getString("BoardNo");
            CPUID=paramBundle.getString("CPUID");
            SpaceSec=paramBundle.getInt("SpaceSec");
            SwitchCount=paramBundle.getInt("SwitchCount");
            curUserPower=new JSONArray(paramBundle.getString("UserPower"));
            System.out.println(paramBundle);
            //暂存Login参数;
            loginParams.clear();
            loginParams.put("ParamComm", "LoginParam");
            loginParams.put("LoginUserNo", curLoginUserNo);
            loginParams.put("LoginUser", curLoginUser);
            loginParams.put("DepartNo", curDepartNo);
            loginParams.put("Depart", curDepart);
            loginParams.put("Factory", curFactory);
            loginParams.put("CPUID",CPUID);
            loginParams.put("BoardNo",BoardNo);
            loginParams.put("PlaceCount",curPlaceCount);
            loginParams.put("OperateTime",curOperateTime);
            loginParams.put("ServiceUrl",serviceUrl+serviceUrlExt);
            loginParams.put("ServiceDir",serviceUrl);
            loginParams.put("SpaceSec",SpaceSec);
            loginParams.put("SwitchCount",SwitchCount);
            //初始化按键，并将页面加载到fragment列表中;
            initView();
            //显示登陆员工;
            btn_LoginUser.setText(curLoginUser);
            title_userNo.setText(curLoginUserNo);
            title_userName.setText(curLoginUser);
            title_depart.setText(curDepart+" ["+curDepartNo+"]");
            title_ConnectState.setText(curLoginTime);
            System.out.println("onCreate ------------------------setText---------2.3");
            //提示框pd=new ProgressDialog(this);
            waitDialog= new ProgressDialog(this);
            waitDialog.setTitle(getString(R.string.SystemHint));
            //接收广播
            try {
                System.out.println("初始化广播发送");
                socket = new MulticastSocket(udpPort);
                receiveAddress=InetAddress.getByName(multicastHost);
                socket.joinGroup(receiveAddress);//加入广播组
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        } catch (Exception e){
            Toast.makeText(this,String.valueOf("出错了，"+e.getMessage()),Toast.LENGTH_LONG).show();
        }
        //全屏
        hideBottomUIMenu();
        //根据权限显示按键,同步加载Fragment，不需要的不加;
        System.out.println("curUserPower:"+curUserPower);
        if (curUserPower!=null)
        {
            if (GetUserFuncPower("FuncA")==1) {
                txt_funcA.setVisibility(View.VISIBLE);
                AddFragment("FragmentA");
            } else txt_funcA.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncB")==1) {
                txt_funcB.setVisibility(View.VISIBLE);
                AddFragment("FragmentB");
            } else txt_funcB.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncC")==1) {
                txt_funcC.setVisibility(View.VISIBLE);
                AddFragment("FragmentC");
            } else txt_funcC.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncD")==1) {
                txt_funcD.setVisibility(View.VISIBLE);
                AddFragment("FragmentD");
            } else txt_funcD.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncE")==1) {
                txt_funcE.setVisibility(View.VISIBLE);
                AddFragment("FragmentE");
            } else txt_funcE.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncF")==1) {
                txt_funcF.setVisibility(View.VISIBLE);
                AddFragment("FragmentF");
            } else txt_funcF.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncG")==1) {
                txt_funcG.setVisibility(View.VISIBLE);
                AddFragment("FragmentG");
            } else txt_funcG.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncH")==1) {
                txt_funcH.setVisibility(View.VISIBLE);
                AddFragment("FragmentH");
            } else txt_funcH.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncI")==1) {
                txt_funcI.setVisibility(View.VISIBLE);
                AddFragment("FragmentI");
            } else txt_funcI.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncJ")==1) {
                txt_funcJ.setVisibility(View.VISIBLE);
                AddFragment("FragmentJ");
            } else txt_funcJ.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncK")==1) {
                txt_funcK.setVisibility(View.VISIBLE);
                AddFragment("FragmentK");
            } else txt_funcK.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncL")==1) {
                txt_funcL.setVisibility(View.VISIBLE);
                AddFragment("FragmentL");
            } else txt_funcL.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncM")==1) {
                txt_funcM.setVisibility(View.VISIBLE);
                AddFragment("FragmentM");
            } else txt_funcM.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncN")==1) {
                txt_funcN.setVisibility(View.VISIBLE);
                AddFragment("FragmentN");
            } else txt_funcN.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncO")==1) {
                txt_funcO.setVisibility(View.VISIBLE);
                AddFragment("FragmentO");
            } else txt_funcO.setVisibility(View.GONE);
            if (GetUserFuncPower("FuncFabric")==1) {
                txt_funcFabric.setVisibility(View.VISIBLE);
                AddFragment("FragmentFabric");
            } else txt_funcFabric.setVisibility(View.GONE);
            //不显示提示;
            if (mFragments.size()>0) findViewById(R.id.frameHintText).setVisibility(View.GONE);
        }
        System.out.println("OnCreate---加载初始Fragment");
        loadDefaultFragment();
        System.out.println("OnCreate---打开串口");
        ExitRun=false;//进入循环;
        System.out.println(CPUID);
        if (!CPUID.toUpperCase().equals("UNKNOW")&&(CPUID.length()>0)) {
            new Thread(this).start();//循环发送；
        }
        //创建服务
        new Handler().postDelayed(new Runnable(){
            public void run(){
                //execute the task
                socketReceiver=new SocketReceiver();
                IntentFilter socketIntentFilter = new IntentFilter();
                socketIntentFilter.addAction(SOCKER_RCV);
                registerReceiver(socketReceiver, socketIntentFilter);
                Intent socketIntent = new Intent();
                socketIntent.setClass(MainActivity.this, SocketService.class);
                // 启动  Socket 服务
                startService(socketIntent);
            }
        },2000);
        System.out.println("OnCreate---Over");

    }


    private void dropAllTable() {
        if (this.mainDB != null) {
            Log.d("Delete", "删除数据库！");
            this.mainDB.execSQL("DROP TABLE IF EXISTS FabricBad");
            this.mainDB.execSQL("DROP TABLE IF EXISTS FabricCode");
            this.mainDB.execSQL("DROP TABLE IF EXISTS QCQuestion");
            this.mainDB.execSQL("DROP TABLE IF EXISTS PartDefine");
            return;
        }
        System.out.println("外部存储不可写!");
    }
    //加载需要用到的Fragment
    private boolean AddFragment(String paramFrgmtName){
        //创建Fragment;
        FragmentStruct tmpFrgmtStruct=new FragmentStruct();
        try {
            Log.d("AddFragment",paramFrgmtName+"--Start");
            tmpFrgmtStruct.frgmt=(Fragment) Class.forName(getPackageName()+"."+paramFrgmtName).newInstance();
            tmpFrgmtStruct.ident=paramFrgmtName;
            mFragments.add(tmpFrgmtStruct);
            Log.d("AddFragment",paramFrgmtName+"--Over");
            return true;
        }catch (ClassNotFoundException err){
            err.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return  false;//未成功加载
    }

    //获取权限,默认都有;
    private int GetUserFuncPower(String paramFunc){
        if (curUserPower.length()>0)
        {
            for (int i=0;i<curUserPower.length();i++){
                if (curUserPower.optJSONObject(i).has(paramFunc)==true)
                {
                    try {
                        return curUserPower.optJSONObject(i).getInt(paramFunc);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
            return 0;
        }
        return 0;
    }

    @Override
    protected void  onStart() {
        super.onStart();
        startTimer();
    }

    //根据顺序预加载Fragment
    private void loadDefaultFragment(){
        curFragmentIndex=-1;
        if (mFragments.size()>0) {
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            Log.d("msg", "Add Fragment------------------------《预加载》");
            for (int i = mFragments.size() - 1; i >= 0; i--) {
                curFragmentIndex = i;
                Log.d("预加载", mFragments.get(curFragmentIndex).ident);
                mContent = mFragments.get(curFragmentIndex).frgmt;
                fragmentTransaction.add(R.id.mFragmentContainer, mContent);
                fragmentTransaction.hide(mContent);
            }
            //提交修改并显示;
            fragmentTransaction.show(mContent);
            fragmentTransaction.commit();

        }
    }
    //Fragment切换

    public void switchFragment(Fragment from, String toFrgmtName) {
        Fragment to=null;
        for (int i=0;i<mFragments.size();i++)
        {
            if (mFragments.get(i).ident.equals(toFrgmtName)==true)
            {
                to=mFragments.get(i).frgmt;
                curFragmentIndex=i;
                break;
            }
        }
        if ((mContent != to)&&(to!=null)) {
            mContent = to;
            FragmentTransaction transaction = fragmentManager.beginTransaction().setCustomAnimations(
                    android.R.anim.slide_in_left,android.R.anim.slide_out_right);
            if (!to.isAdded()) {    // 先判断是否被add过
                transaction.hide(from).add(R.id.mFragmentContainer, to).commit(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(from).show(to).commit(); // 隐藏当前的fragment，显示下一个
            }
        }

    }

    private void initView()
    {
        txt_titleInv=findViewById(R.id.txt_titleInv);
        title_userNo=findViewById(R.id.title_userNo);
        title_userName=findViewById(R.id.title_userName);
        title_depart=findViewById(R.id.title_depart);
        title_ConnectState =findViewById(R.id.title_ConnectState);
        //顶端图标;
        titleImgView=findViewById(R.id.titleImgView);
        titleImgView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //将临时文件复制到SD卡;
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    Log.d("MSG-getDatabasePath",getDatabasePath(DB_Name).toString());
                    Log.d("MSG-getDataDirectory",getDataDirectory().toString());
                    Log.d("MSG-StorageDirectory", getExternalStorageDirectory().toString());
                    //将数据复制到SD卡;
                    copyFile(getDatabasePath(DB_Name).toString(),SaveFilePath+SaveDBFolder+"/"+DB_Name);
                    copyFolder(getCacheDir().toString(),SaveFilePath);
                }

            }
        });
        titleImgView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                AlertDialog alertDialog = new AlertDialog.Builder(v.getContext())
                        .setTitle("系统提示").setMessage("您确定要从临时数据复制到外部存储中吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                //将临时文件复制到SD卡;
                                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                                    Log.d("MSG-getDatabasePath",getDatabasePath(DB_Name).toString());
                                    Log.d("MSG-getDataDirectory",getDataDirectory().toString());
                                    Log.d("MSG-StorageDirectory", getExternalStorageDirectory().toString());
                                    //将SD卡数据复制到数据目录;
                                    String docfilePath=getCacheDir().toString()+"/AD14431.DOC";
                                    System.out.println("源文件:"+docfilePath);
                                    System.out.println("目标文件:"+SaveFilePath+SaveDBFolder+"/AD14431.DOC");
                                    copyFile(docfilePath,SaveFilePath+SaveDBFolder+"/AD14431.DOC");
                                    //copyFile(SaveFilePath+SaveDBFolder+"/"+DB_Name,getDatabasePath(DB_Name).toString());
                                    copyFile(getDatabasePath(DB_Name).toString(),SaveFilePath+SaveDBFolder+"/"+DB_Name);

                                }
                            }

                        }).setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create(); // 创建对话框
                alertDialog.show(); // 显示对话框
                return false;
            }
        });
        //下边栏按钮
        txt_funcA=findViewById(R.id.txt_funcA);
        txt_funcB=findViewById(R.id.txt_funcB);
        txt_funcC=findViewById(R.id.txt_funcC);
        txt_funcD=findViewById(R.id.txt_funcD);
        txt_funcE=findViewById(R.id.txt_funcE);
        txt_funcF=findViewById(R.id.txt_funcF);
        txt_funcG=findViewById(R.id.txt_funcG);
        txt_funcH=findViewById(R.id.txt_funcH);
        txt_funcI=findViewById(R.id.txt_funcI);
        txt_funcJ=findViewById(R.id.txt_funcJ);
        txt_funcK=findViewById(R.id.txt_funcK);
        txt_funcL=findViewById(R.id.txt_funcL);
        txt_funcM=findViewById(R.id.txt_funcM);
        txt_funcN=findViewById(R.id.txt_funcN);
        txt_funcO=findViewById(R.id.txt_funcO);
        txt_funcFabric=findViewById(R.id.txt_funcFabric);
        //设置监听;
        txt_funcA.setOnClickListener(this);
        txt_funcB.setOnClickListener(this);
        txt_funcC.setOnClickListener(this);
        txt_funcD.setOnClickListener(this);
        txt_funcE.setOnClickListener(this);
        txt_funcF.setOnClickListener(this);
        txt_funcG.setOnClickListener(this);
        txt_funcH.setOnClickListener(this);
        txt_funcI.setOnClickListener(this);
        txt_funcJ.setOnClickListener(this);
        txt_funcK.setOnClickListener(this);
        txt_funcL.setOnClickListener(this);
        txt_funcM.setOnClickListener(this);
        txt_funcN.setOnClickListener(this);
        txt_funcO.setOnClickListener(this);
        txt_funcFabric.setOnClickListener(this);
        //退出
        btn_LoginUser=findViewById(R.id.btn_LoginUser);
        btn_LoginClose =findViewById(R.id.btn_LoginClose);
        btn_LoginClose.setOnClickListener(this);
        btn_LoginClose.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                dropAllTable();
                return false;
            }
        });
        //初始提醒;
        curToast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG);
        curToast.setGravity(Gravity.CENTER, 0, 0);
        //创建临时表;
        CreateDBTable();

    }


    //传递参数到MainFragment
    private void sendParamFragmentA() {
        Log.d("SendParam", "sendParamFragmentA------------------Enter;");
        if (transParamsListenerA != null) {
            Log.d("SendParam", "sendParamFragmentA------------------1;");
            transParamsListenerA.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentA------------------2;");
        }
    }

    //传递参数到MainFragment
    private void sendParamFragmentB() {
        Log.d("SendParam", "sendParamFragmentB------------------Enter;");
        if (transParamsListenerB != null) {
            Log.d("SendParam", "sendParamFragmentB------------------1;");
            transParamsListenerB.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentB------------------2;");
        }
    }

    //传递参数到MainFragment
    private void sendParamFragmentC() {
        Log.d("SendParam", "sendParamFragmentC------------------Enter;");
        if (transParamsListenerC != null) {
            Log.d("SendParam", "sendParamFragmentC------------------1;");
            transParamsListenerC.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentC------------------2;");
        }
    }


    //传递参数到MainFragment
    private void sendParamFragmentCWeight(String paramWeight) {
        Map<String,Object> lightParams=new HashMap<String,Object>();
        //Log.d("SendParam", "sendParamFragmentEConLight------------------Enter;");
        if (transParamsListenerC != null) {
            //Log.d("SendParam", "sendParamFragmentEConLight------------------1;");
            lightParams.clear();
            lightParams.put("ParamComm", "Weight");
            lightParams.put("Weight", paramWeight);
            transParamsListenerC.TransParams(lightParams);
            //Log.d("SendParam", "sendParamFragmentEConLight------------------2;");
        }
    }

    //传递参数到MainFragment
    private void sendParamFragmentFabricWeight(String paramWeight) {
        Map<String,Object> lightParams=new HashMap<String,Object>();
        //Log.d("SendParam", "sendParamFragmentEConLight------------------Enter;");
        if (transParamsListenerFabric != null) {
            //Log.d("SendParam", "sendParamFragmentEConLight------------------1;");
            lightParams.clear();
            lightParams.put("ParamComm", "Weight");
            lightParams.put("Weight", paramWeight);
            transParamsListenerFabric.TransParams(lightParams);
            //Log.d("SendParam", "sendParamFragmentEConLight------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentLCmd(String paramCmd) {
        Map<String,Object> lightParams=new HashMap<String,Object>();
        if (transParamsListenerL != null) {
            //Log.d("SendParam", "transParamsListenerL------------------1;");
            lightParams.clear();
            lightParams.put("ParamComm", paramCmd);
            transParamsListenerL.TransParams(lightParams);
            //Log.d("SendParam", "sendParamFragmentEConLight------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentOCmd(String paramCmd) {
        Map<String,Object> lightParams=new HashMap<String,Object>();
        if (transParamsListenerO != null) {
            //Log.d("SendParam", "transParamsListenerL------------------1;");
            lightParams.clear();
            lightParams.put("ParamComm", paramCmd);
            transParamsListenerO.TransParams(lightParams);
            //Log.d("SendParam", "sendParamFragmentEConLight------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentD() {
        Log.d("SendParam", "sendParamFragmentD------------------Enter;");
        if (transParamsListenerD != null) {
            Log.d("SendParam", "sendParamFragmentD------------------1;");
            transParamsListenerD.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentD------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentE() {
        Log.d("SendParam", "sendParamFragmentE------------------Enter;");
        if (transParamsListenerE != null) {
            Log.d("SendParam", "sendParamFragmentE------------------1;");
            transParamsListenerE.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentE------------------2;");
        }
    }

    //传递参数到MainFragment
    private void sendParamFragmentF() {
        Log.d("SendParam", "sendParamFragmentF------------------Enter;");
        if (transParamsListenerF != null) {
            Log.d("SendParam", "sendParamFragmentF------------------1;");
            transParamsListenerF.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentF------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentG() {
        Log.d("SendParam", "sendParamFragmentG------------------Enter;");
        if (transParamsListenerG != null) {
            Log.d("SendParam", "sendParamFragmentG------------------1;");
            transParamsListenerG.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentG------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentH() {
        Log.d("SendParam", "sendParamFragmentH------------------Enter;");
        if (transParamsListenerH != null) {
            Log.d("SendParam", "sendParamFragmentH------------------1;");
            transParamsListenerH.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentH------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentI() {
        Log.d("SendParam", "sendParamFragmentI------------------Enter;");
        if (transParamsListenerI != null) {
            Log.d("SendParam", "sendParamFragmentI------------------1;");
            transParamsListenerI.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentI------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentJ() {
        Log.d("SendParam", "sendParamFragmentJ------------------Enter;");
        if (transParamsListenerJ != null) {
            Log.d("SendParam", "sendParamFragmentJ------------------1;");
            transParamsListenerJ.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentJ------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentK() {
        Log.d("SendParam", "sendParamFragmentK------------------Enter;");
        if (transParamsListenerK != null) {
            Log.d("SendParam", "sendParamFragmentK------------------1;");
            transParamsListenerK.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentK------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentL() {
        Log.d("SendParam", "sendParamFragmentL------------------Enter;");
        if (transParamsListenerL != null) {
            Log.d("SendParam", "sendParamFragmentL------------------1;");
            transParamsListenerL.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentL------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentM() {
        Log.d("SendParam", "sendParamFragmentM------------------Enter;");
        if (transParamsListenerM != null) {
            Log.d("SendParam", "sendParamFragmentM------------------1;");
            transParamsListenerM.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentM------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentN() {
        Log.d("SendParam", "sendParamFragmentN------------------Enter;");
        if (transParamsListenerN != null) {
            Log.d("SendParam", "sendParamFragmentN------------------1;");
            transParamsListenerN.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentN------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentO() {
        Log.d("SendParam", "sendParamFragmentO------------------Enter;");
        if (transParamsListenerO != null) {
            Log.d("SendParam", "sendParamFragmentO------------------1;");
            transParamsListenerO.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentO------------------2;");
        }
    }

    //传递参数到MainFragment
    private void sendParamFragmentFabric() {
        Log.d("SendParam", "sendParamFragmentFabric------------------Enter;");
        if (transParamsListenerFabric != null) {
            Log.d("SendParam", "sendParamFragmentFabric------------------1;");
            transParamsListenerFabric.TransParams(loginParams);
            Log.d("SendParam", "sendParamFragmentFabric------------------2;");
        }
    }
    /**
     * 定义一个Handler用于接收Fragment给Activity发出来的指令
     */
    public Handler mainHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                switch (msg.what) {
                    case MSG_UpdateSocket:
                        if (SocketConnected==true) {
                            ((TextView)findViewById(R.id.title_ConnectState)).setText("吊挂已连接..");
                            ((TextView)findViewById(R.id.title_ConnectState)).setTextColor(getResources().getColor(R.color.white));
                        }
                        else {
                            ((TextView)findViewById(R.id.title_ConnectState)).setText("吊挂尚未连接...");
                            ((TextView)findViewById(R.id.title_ConnectState)).setTextColor(getResources().getColor(R.color.red));
                        }
                        break;
                    case getParamFragmentA:

                        break;
                    case getParamFragmentB:

                        break;
                    case getParamFragmentC:

                        break;
                    case getParamFragmentD:
                        //mViewPager.setCurrentItem(0,true);
                        break;
                    case getParamFragmentE:
                        //mViewPager.setCurrentItem(1,true);
                        break;
                    case getParamFragmentF:
                        //mViewPager.setCurrentItem(2,true);
                        break;
                    default:
                        break;
                }
            }
        }
    };


    private void CreateDBTable() {
        SQLiteDatabase sQLiteDatabase = this.mainDB;
        if (sQLiteDatabase != null) {
            sQLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS FabricBad (ID INTEGER PRIMARY KEY AUTOINCREMENT,FabricDeID VARCHAR,FabricCode VARCHAR,FabricQuestion VARCHAR,Place VARCHAR,Deduct VARCHAR)");
            this.mainDB.execSQL("CREATE TABLE IF NOT EXISTS FabricCode (ID INTEGER PRIMARY KEY AUTOINCREMENT,FabricCode VARCHAR,FabricQuestion VARCHAR)");
            this.mainDB.execSQL("CREATE TABLE IF NOT EXISTS QCQuestion (ID INTEGER PRIMARY KEY AUTOINCREMENT,QuestionNo VARCHAR,QuestionCode VARCHAR,TypeIndex int,QuestionType VARCHAR)");
            this.mainDB.execSQL("CREATE TABLE IF NOT EXISTS PartDefine (ID INTEGER PRIMARY KEY AUTOINCREMENT,PartName VARCHAR,PosX REAL,PosY REAL)");
        }
    }


    //获取当前显示的Fragment
    public Fragment getVisibleFragment() {
        FragmentManager fragmentManager;
        fragmentManager = MainActivity.this.getSupportFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        for (Fragment fragment : fragments) {
            if (fragment != null && fragment.isVisible())
                return fragment;
        }
        return null;
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    //重置所有文本的选中状态
    public void unSelected(){
        txt_funcA.setSelected(false);
        txt_funcA.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcB.setSelected(false);
        txt_funcB.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcC.setSelected(false);
        txt_funcC.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcD.setSelected(false);
        txt_funcD.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcE.setSelected(false);
        txt_funcE.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcF.setSelected(false);
        txt_funcF.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcG.setSelected(false);
        txt_funcG.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcH.setSelected(false);
        txt_funcH.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcI.setSelected(false);
        txt_funcI.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcJ.setSelected(false);
        txt_funcJ.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcK.setSelected(false);
        txt_funcK.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcL.setSelected(false);
        txt_funcL.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcM.setSelected(false);
        txt_funcM.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcN.setSelected(false);
        txt_funcN.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcO.setSelected(false);
        txt_funcO.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcFabric.setSelected(false);
        txt_funcFabric.setTextColor(getResources().getColor(R.color.text_gray));
    }
    public void Selected(TextView paramBtn){
        paramBtn.setSelected(true);
        paramBtn.setTextColor(getResources().getColor(R.color.text_main));
        txt_titleInv.setText(paramBtn.getText());
    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }
    @Override
    public void onClick(View v) {
        hideIM(v);
        hideBottomUIMenu();
        switch (v.getId()){
            case R.id.txt_funcA:
                unSelected();
                Selected(txt_funcA);
                switchFragment(mContent, "FragmentA");
                sendParamFragmentA();
                break;
            case R.id.txt_funcB:
                unSelected();
                Selected(txt_funcB);
                switchFragment(mContent, "FragmentB");
                sendParamFragmentB();
                break;
            case R.id.txt_funcC:
                unSelected();
                Selected(txt_funcC);
                switchFragment(mContent, "FragmentC");
                sendParamFragmentC();
                break;
            case R.id.txt_funcD:
                unSelected();
                Selected(txt_funcD);
                switchFragment(mContent, "FragmentD");
                sendParamFragmentD();
                break;
            case R.id.txt_funcE:
                unSelected();
                Selected(txt_funcE);
                switchFragment(mContent, "FragmentE");
                sendParamFragmentE();
                break;
            case R.id.txt_funcF:
                unSelected();
                Selected(txt_funcF);
                switchFragment(mContent, "FragmentF");
                sendParamFragmentF();
                break;
            case R.id.txt_funcG:
                unSelected();
                Selected(txt_funcG);
                switchFragment(mContent, "FragmentG");
                sendParamFragmentG();
                break;
            case R.id.txt_funcH:
                unSelected();
                Selected(txt_funcH);
                switchFragment(mContent, "FragmentH");
                sendParamFragmentH();
                break;
            case R.id.txt_funcI:
                unSelected();
                Selected(txt_funcI);
                switchFragment(mContent, "FragmentI");
                sendParamFragmentI();
                break;
            case R.id.txt_funcJ:
                unSelected();
                Selected(txt_funcJ);
                switchFragment(mContent, "FragmentJ");
                sendParamFragmentJ();
                break;
            case R.id.txt_funcK:
                unSelected();
                Selected(txt_funcK);
                switchFragment(mContent, "FragmentK");
                sendParamFragmentK();
                break;
            case R.id.txt_funcL:
                unSelected();
                Selected(txt_funcL);
                switchFragment(mContent, "FragmentL");
                sendParamFragmentL();
                break;
            case R.id.txt_funcM:
                unSelected();
                Selected(txt_funcM);
                switchFragment(mContent, "FragmentM");
                sendParamFragmentM();
                break;
            case R.id.txt_funcN:
                unSelected();
                Selected(txt_funcN);
                switchFragment(mContent, "FragmentN");
                sendParamFragmentN();
                break;
            case R.id.txt_funcO:
                unSelected();
                Selected(txt_funcO);
                switchFragment(mContent, "FragmentO");
                sendParamFragmentO();
                break;
            case R.id.txt_funcFabric:
                unSelected();
                Selected(txt_funcFabric);
                switchFragment(mContent, "FragmentFabric");
                sendParamFragmentFabric();
                break;
            case R.id.btn_LoginClose:
                finish();//关闭当前Activity，返回上一级;
                break;
        }
    }

    //判断外部存储是否可读写
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }





    /**
     * 复制单个文件
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ( (byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        }
        catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }

    /**
     * 复制整个文件夹内容
     * @param oldPath String 原文件路径 如：c:/fqf
     * @param newPath String 复制后路径 如：f:/fqf/ff
     * @return boolean
     */
    public void copyFolder(String oldPath, String newPath) {

        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a=new File(oldPath);
            String[] file=a.list();
            File temp=null;
            for (int i = 0; i < file.length; i++) {
                if(oldPath.endsWith(File.separator)){
                    temp=new File(oldPath+file[i]);
                }
                else{
                    temp=new File(oldPath+File.separator+file[i]);
                }

                if(temp.isFile()){
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ( (len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if(temp.isDirectory()){//如果是子文件夹
                    copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
                }
            }
        }
        catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }

    }

    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+this.getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("系统提示","OnPause");
        closeSerialPort();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("系统提示","onResume");
        hideBottomUIMenu();
        System.out.println("onResume--Start");
        /*增减功能时这里要同步修改*/
        if (curFragmentIndex>-1){
            System.out.println("curFragmentIndex:"+curFragmentIndex);
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentA")) {Selected(txt_funcA);sendParamFragmentA();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentB")) {Selected(txt_funcB);sendParamFragmentB();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentC")) {Selected(txt_funcC);sendParamFragmentC();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentD")) {Selected(txt_funcD);sendParamFragmentD();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentE")) {Selected(txt_funcE);sendParamFragmentE();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentF")) {Selected(txt_funcF);sendParamFragmentF();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentG")) {Selected(txt_funcG);sendParamFragmentG();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentH")) {Selected(txt_funcH);sendParamFragmentH();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentI")) {Selected(txt_funcI);sendParamFragmentI();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentJ")) {Selected(txt_funcJ);sendParamFragmentJ();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentK")) {Selected(txt_funcK);sendParamFragmentK();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentL")) {Selected(txt_funcL);sendParamFragmentL();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentM")) {Selected(txt_funcM);sendParamFragmentM();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentN")) {Selected(txt_funcN);sendParamFragmentN();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentO")) {Selected(txt_funcO);sendParamFragmentN();}
            if (mFragments.get(curFragmentIndex).ident.equals("FragmentFabric")) {Selected(txt_funcFabric);sendParamFragmentFabric();}

        }
        System.out.println("onResume--Over");
        if (!CPUID.toUpperCase().equals("UNKNOW")&&(CPUID.length()>0)) {
            openSrialPort();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeSerialPort();
        Log.d("调试","onDestroy");
        ExitRun=true;
        receiveFlag=false;
        mainHandler.removeCallbacksAndMessages(null);
        stopTimer();
        Log.d("msg","MainActivity OnDestroy------------------------");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("系统提示","onRestart");
        if (!CPUID.toUpperCase().equals("UNKNOW")&&(CPUID.length()>0)) {
            openSrialPort();
        }
    }
}
